//
//  DownloadTableViewCell.m
//  CapriceMusic
//
//  Created by dllo on 16/1/12.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "DownloadTableViewCell.h"
#import "DownLoadManager.h"
@implementation DownloadTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.coverPic = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self addSubview:self.coverPic];
        
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        [self addSubview:self.titleLabel];
        
        self.button = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.button addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchUpInside];
        [self.button setBackgroundImage:[UIImage imageNamed:@"stopdownload"] forState:UIControlStateNormal];
        [self addSubview:self.button];
        
        self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        [self addSubview:self.progressView];
        
        self.progressLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        [self addSubview:self.progressLabel];
        
    }
    return self;
}

- (void)buttonDidPress:(UIButton *)sender {
    DownLoadManager *download = [DownLoadManager shareDownLoadManager];
    if (self.pause == 0) {
        [download.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            [download setResumeData:resumeData];
            download.downloadTask = nil;
        }];
        [sender setBackgroundImage:[UIImage imageNamed:@"startdownload"] forState:UIControlStateNormal];
    } else if (self.pause == 1) {
        download.downloadTask = [download.session downloadTaskWithResumeData:download.resumeData];
        [download.downloadTask resume];
        [download setResumeData:nil];
        [sender setBackgroundImage:[UIImage imageNamed:@"stopdownload"] forState:UIControlStateNormal];
    }
    self.pause = !self.pause;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.coverPic.frame = CGRectMake(0, 0, self.frame.size.width / 3, self.frame.size.height);
    self.titleLabel.frame = CGRectMake(self.frame.size.width / 3 + 20 , 10, self.frame.size.width / 2, 20);
    self.button.frame = CGRectMake(self.frame.size.width / 1.2, 30, 30, 30);
    self.progressView.frame = CGRectMake(self.frame.size.width / 3 + 20, 50, 100, 20);
    self.progressLabel.frame = CGRectMake(self.frame.size.width / 3 + 20, 70, 100, 20);
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}

@end
